import { ref, nextTick } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { debounce, throttle } from 'lodash'
import { customerApi } from '@/api/customer'
import type {
  Customer,
  CustomerContact,
  CustomerTrace,
  CustomerChance,
  CustomerLog,
} from '@/types/customer'
import type { ApiResponse } from '@/types/api'
import request from '@/utils/request'
import { statusService } from '@/utils/statusService'

// 请求状态管理，避免重复请求
const requestStates = ref<Record<string, boolean>>({})
const requestCache = ref<Record<string, any>>({})

// 数据相关
const customerData = ref<Customer | null>(null)
const activeTab = ref<string>('contact')
const contactList = ref<CustomerContact[]>([])
const traceList = ref<CustomerTrace[]>([])
const chanceList = ref<CustomerChance[]>([])
const logList = ref<CustomerLog[]>([])
const contractList = ref<any[]>([])
const caseList = ref<any[]>([])
const subCustomerList = ref<Customer[]>([])
const loading = ref<boolean>(false)

// 联系人操作相关
const contactDrawerVisible = ref<boolean>(false)
const contactOperationMode = ref<'add' | 'edit'>('add')
const currentContactId = ref<number | string>('')

// 跟进记录操作相关
const traceDrawerVisible = ref<boolean>(false)
const traceOperationMode = ref<'add' | 'edit' | 'view'>('add')
const currentTraceId = ref<number | string>('')

// 合同操作相关
const contractDrawerVisible = ref<boolean>(false)

// 案件操作相关
const caseDrawerVisible = ref<boolean>(false)

// 返回上一页
const goBack = (router: any) => {
  router.back()
}

// 获取地区名称
const getRegionName = (row: any) => {
  return `${row.province_name || ''}${row.city_name || ''}${row.district_name || ''}`
}

// 获取销售机会阶段名称
const getChanceStageName = (stage: number) => {
  const stageMap: Record<number, string> = {
    1: '初步接触',
    2: '需求分析',
    3: '方案报价',
    4: '商务谈判',
    5: '成交',
    6: '失败',
  }

  return stageMap[stage] || '未知'
}

// 格式化金额
const formatAmount = (amount: number | string | undefined) => {
  if (amount === undefined || amount === null) return '¥0.00'
  const num = parseFloat(String(amount))
  if (isNaN(num)) return '¥0.00'
  return `¥${num.toLocaleString('zh-CN', { minimumFractionDigits: 2, maximumFractionDigits: 2 })}`
}

// 统一处理客户数据的默认值和格式
const processCustomerData = (customerInfo: any) => {
  // 保留customer_status数字字段，仅处理customer_status_name
  if (!customerInfo.customer_status_name) {
    customerInfo.customer_status_name =
      statusService.getCustomerStatusName(customerInfo.customer_status) || '未设置'
  }

  // 为所有字段提供默认值，避免空值显示
  const defaultFields = [
    'name',
    'address',
    'tax_num',
    'tax_bank',
    'tax_banksn',
    'tax_mobile',
    'tax_address',
    'customer_status_name',
    'source_name',
    'grade_name',
    'belong_name',
    'belong_department',
    'share_names',
    'controller_name',
    'relation_desc',
    'follow_time',
    'description',
    'province_name',
    'city_name',
    'district_name',
  ]

  defaultFields.forEach(field => {
    if (
      customerInfo[field] === undefined ||
      customerInfo[field] === null ||
      customerInfo[field] === ''
    ) {
      // 根据字段类型设置不同的默认值
      if (['controller_name', 'relation_desc'].includes(field)) {
        customerInfo[field] = customerInfo[field] || '-'
      } else if (['province_name', 'city_name', 'district_name'].includes(field)) {
        customerInfo[field] = customerInfo[field] || ''
      } else {
        customerInfo[field] = customerInfo[field] || '未设置'
      }
    }
  })

  // 确保数字字段有默认值
  if (customerInfo.contract_num === undefined || customerInfo.contract_num === null) {
    customerInfo.contract_num = 0
  }
  if (customerInfo.contract_amount === undefined || customerInfo.contract_amount === null) {
    customerInfo.contract_amount = 0
  }

  return customerInfo
}

// 防重复请求的工具函数
const generateRequestKey = (functionName: string, params: any) => {
  return `${functionName}_${JSON.stringify(params)}`
}

const markRequestAsPending = (key: string) => {
  requestStates.value[key] = true
}

const markRequestAsCompleted = (key: string) => {
  delete requestStates.value[key]
}

const isRequestPending = (key: string) => {
  return requestStates.value[key] === true
}

const setCache = (key: string, data: any) => {
  requestCache.value[key] = data
}

const getCache = (key: string) => {
  return requestCache.value[key]
}

// 处理Tab切换
const handleTabChange = async (tabName: string, route: any) => {
  const customerId = route.params.id as string
  if (!customerId) return

  switch (tabName) {
    case 'contact':
      await loadContactList(parseInt(customerId))
      break
    case 'trace':
      await loadTraceList(parseInt(customerId))
      break
    case 'chance':
      await loadChanceList(parseInt(customerId))
      break
    case 'contract':
      await loadContractList(parseInt(customerId))
      break
    case 'lawcase':
      await loadCaseList(parseInt(customerId))
      break
    case 'log':
      await loadLogList(parseInt(customerId))
      break
  }
}

// 加载客户详情（整合多表信息）- 防重复请求版本
const loadCustomerDetail = async (customerId: number) => {
  if (!customerId) return

  const requestKey = generateRequestKey('getCustomerDetail', { customerId, contract_workflow: 1 })

  // 检查是否已有相同的请求正在进行
  if (isRequestPending(requestKey)) {
    return
  }

  // 检查是否有缓存数据可以使用（缓存5分钟）
  const cachedData = getCache(requestKey)
  if (cachedData && Date.now() - (cachedData.timestamp || 0) < 5 * 60 * 1000) {
    customerData.value = cachedData.data
    return cachedData.data
  }

  markRequestAsPending(requestKey)

  try {
    // 使用新的API，一次调用获取所有信息（传递contract_workflow=1以绕过权限检查）
    const response = await customerApi.getCustomerDetail({ id: customerId, contract_workflow: 1 })

    if (response && response.code === 0 && response.data) {
      const customerInfo = response.data

      // 确保客户等级和状态正确
      if (!customerInfo.grade_name && customerInfo.grade_id) {
        customerInfo.grade_name = `等级${customerInfo.grade_id}`
      }

      if (!customerInfo.customer_status_name) {
        customerInfo.customer_status_name = '未设置'
      }

      // 统一处理客户数据，设置默认值和格式
      processCustomerData(customerInfo)

      // 如果有管家ID但没有管家名称，尝试获取管家姓名
      if (customerInfo.belong_uid && !customerInfo.belong_name) {
        try {
          const adminListResponse = await customerApi.getAdminList()
          // 修正API响应处理的类型错误
          if (Array.isArray(adminListResponse)) {
            const admin = adminListResponse.find(
              item => String(item.id) === String(customerInfo.belong_uid)
            )
            if (admin) {
              customerInfo.belong_name = admin.name
            }
          }
        } catch (error) {
          // 忽略错误
        }
      }

      // 从响应中提取关联数据 - 修正属性名称和类型
      if (customerInfo.contacter) {
        // 确保contactList.value是正确的数组类型
        contactList.value = Array.isArray(customerInfo.contacter) ? customerInfo.contacter : []
      }
      // 假设traces和chances可能存在于customerInfo的其他属性中或需要单独加载
      // 如果是需要单独加载的情况，应该在loadTraceList和loadChanceList函数中处理

      customerData.value = customerInfo

      // 缓存数据
      setCache(requestKey, {
        data: customerInfo,
        timestamp: Date.now(),
      })

      // 加载当前活动标签页的数据，但避免重复加载联系人列表
      // 如果当前标签是contact，且已经从customerInfo获取了联系人数据，则跳过loadContactList
      if (activeTab.value !== 'contact' || !customerInfo.contacter) {
        await handleTabChange(activeTab.value, { params: { id: customerId.toString() } })
      }
    } else {
      ElMessage.error(response?.msg || '获取客户详情失败')
      // 创建默认客户数据 - 包含所有必要属性
      const defaultCustomerData = {
        id: parseInt(customerId.toString()),
        name: '数据加载中...',
        address: '',
        tax_num: '',
        tax_bank: '',
        tax_banksn: '',
        tax_mobile: '',
        tax_address: '',
        contact_name: '',
        contact_mobile: '',
        belong_uid: 0,
        belong_name: '',
        belong_did: 0,
        is_lock: 0,
        create_time: '',
        update_time: '',
        delete_time: 0,
        contract_num: 0,
        contract_amount: 0,
        is_primary: 0,
        group_code: '',
        // 添加其他可能需要的属性
        grade_id: 0,
        grade_name: '',
        customer_status: 0,
        customer_status_name: '未设置',
      }
      processCustomerData(defaultCustomerData)
      customerData.value = defaultCustomerData as any
    }
  } catch (error: any) {
    // 忽略请求被取消的错误（ERR_CANCELED），这通常发生在组件卸载时
    if (error.code === 'ERR_CANCELED') {
      console.log('请求被取消，跳过错误处理')
      return
    }
    console.error('获取客户详情失败:', error)
    ElMessage.error('获取客户详情失败')
    // 创建默认客户数据 - 包含所有必要属性
    const defaultCustomerData = {
      id: parseInt(customerId.toString()),
      name: '数据加载失败',
      address: '',
      tax_num: '',
      tax_bank: '',
      tax_banksn: '',
      tax_mobile: '',
      tax_address: '',
      contact_name: '',
      contact_mobile: '',
      belong_uid: 0,
      belong_name: '',
      belong_did: 0,
      is_lock: 0,
      create_time: '',
      update_time: '',
      delete_time: 0,
      contract_num: 0,
      contract_amount: 0,
      is_primary: 0,
      group_code: '',
      // 添加其他可能需要的属性
      grade_id: 0,
      grade_name: '',
      customer_status: 0,
      customer_status_name: '未设置',
    }
    processCustomerData(defaultCustomerData)
    customerData.value = defaultCustomerData as any
  } finally {
    markRequestAsCompleted(requestKey)
  }
}

// 加载联系人列表 - 防重复请求版本
const loadContactList = async (customerId: number) => {
  if (!customerId) return

  const requestKey = generateRequestKey('getContactList', { customer_id: customerId })

  // 检查是否已有相同的请求正在进行
  if (isRequestPending(requestKey)) {
    return
  }

  // 检查是否有缓存数据可以使用（缓存5分钟）
  const cachedData = getCache(requestKey)
  if (cachedData && Date.now() - (cachedData.timestamp || 0) < 5 * 60 * 1000) {
    contactList.value = cachedData.data
    return cachedData.data
  }

  markRequestAsPending(requestKey)

  try {
    // 注意：联系人API使用customer_id作为参数名，而不是cid
    const response = await customerApi.getContactList({ customer_id: customerId })
    if (response && response.code === 0) {
      const contactData = response.data?.list || []
      contactList.value = contactData

      // 缓存数据
      setCache(requestKey, {
        data: contactData,
        timestamp: Date.now(),
      })
    } else {
      contactList.value = []
      // 添加更详细的错误信息
      const errorMessage = response?.msg || '获取联系人列表失败'
      ElMessage.error(errorMessage)
      console.error('获取联系人列表失败:', response)
    }
  } catch (error: any) {
    contactList.value = []
    // 忽略请求被取消的错误（ERR_CANCELED），这通常发生在组件卸载或重复请求时
    if (error.code === 'ERR_CANCELED') {
      console.log('获取联系人列表请求被取消，忽略该错误')
      return
    }
    // 处理网络错误或服务器错误
    const errorMessage = error instanceof Error ? error.message : '获取联系人列表失败'
    console.error('获取联系人列表失败:', error)
    ElMessage.error(errorMessage)
  } finally {
    markRequestAsCompleted(requestKey)
  }
}

// 加载跟进记录列表 - 防重复请求版本
const loadTraceList = async (customerId: number) => {
  if (!customerId) return

  const requestKey = generateRequestKey('getTraceList', { cid: customerId })

  // 检查是否已有相同的请求正在进行
  if (isRequestPending(requestKey)) {
    return
  }

  // 检查是否有缓存数据可以使用（缓存5分钟）
  const cachedData = getCache(requestKey)
  if (cachedData && Date.now() - (cachedData.timestamp || 0) < 5 * 60 * 1000) {
    traceList.value = cachedData.data
    return cachedData.data
  }

  markRequestAsPending(requestKey)

  try {
    // 注意：跟进记录API使用cid作为参数名，而不是customer_id
    const response: ApiResponse<CustomerTrace[]> = await customerApi.getTraceList({
      cid: customerId,
    })
    if (response && response.code === 0) {
      const traceData = response.data || []
      traceList.value = traceData

      // 缓存数据
      setCache(requestKey, {
        data: traceData,
        timestamp: Date.now(),
      })
    } else {
      traceList.value = []
      // 添加更详细的错误信息
      const errorMessage = response?.msg || '获取跟进记录列表失败'
      ElMessage.error(errorMessage)
      console.error('获取跟进记录列表失败:', response)
    }
  } catch (error) {
    traceList.value = []
    // 处理网络错误或服务器错误
    const errorMessage = error instanceof Error ? error.message : '获取跟进记录列表失败'
    console.error('获取跟进记录列表失败:', error)
    ElMessage.error(errorMessage)
  } finally {
    markRequestAsCompleted(requestKey)
  }
}

// 加载销售机会列表 - 防重复请求版本
const loadChanceList = async (customerId: number) => {
  if (!customerId) return

  const requestKey = generateRequestKey('getChanceList', { cid: customerId })

  // 检查是否已有相同的请求正在进行
  if (isRequestPending(requestKey)) {
    return
  }

  // 检查是否有缓存数据可以使用（缓存5分钟）
  const cachedData = getCache(requestKey)
  if (cachedData && Date.now() - (cachedData.timestamp || 0) < 5 * 60 * 1000) {
    chanceList.value = cachedData.data
    return cachedData.data
  }

  markRequestAsPending(requestKey)

  try {
    // 注意：销售机会API使用cid作为参数名，而不是customer_id
    const response: ApiResponse<any> = await customerApi.getChanceList({ cid: customerId })
    if (response && response.code === 0) {
      // 销售机会API返回的数据结构是 { list: [], total: ... }, 所以需要取response.data.list
      const chanceData = Array.isArray(response.data?.list) ? response.data.list : []
      chanceList.value = chanceData

      // 缓存数据
      setCache(requestKey, {
        data: chanceData,
        timestamp: Date.now(),
      })
    } else {
      chanceList.value = []
      // 添加更详细的错误信息
      const errorMessage = response?.msg || '获取销售机会列表失败'
      ElMessage.error(errorMessage)
      console.error('获取销售机会列表失败:', response)
    }
  } catch (error) {
    chanceList.value = []
    // 处理网络错误或服务器错误
    const errorMessage = error instanceof Error ? error.message : '获取销售机会列表失败'
    console.error('获取销售机会列表失败:', error)
    ElMessage.error(errorMessage)
  } finally {
    markRequestAsCompleted(requestKey)
  }
}

// 加载操作日志列表 - 防重复请求版本
const loadLogList = async (customerId: number) => {
  if (!customerId) return

  const requestKey = generateRequestKey('getLogList', { customer_id: customerId })

  // 检查是否已有相同的请求正在进行
  if (isRequestPending(requestKey)) {
    return
  }

  // 检查是否有缓存数据可以使用（缓存5分钟）
  const cachedData = getCache(requestKey)
  if (cachedData && Date.now() - (cachedData.timestamp || 0) < 5 * 60 * 1000) {
    logList.value = cachedData.data
    return cachedData.data
  }

  markRequestAsPending(requestKey)

  try {
    // 注意：操作日志API使用customer_id作为参数名，而不是cid
    const response: ApiResponse<CustomerLog[]> = await customerApi.getLogList({
      customer_id: customerId,
    })
    if (response && response.code === 0) {
      const logData = response.data || []
      logList.value = logData

      // 缓存数据
      setCache(requestKey, {
        data: logData,
        timestamp: Date.now(),
      })
    } else {
      logList.value = []
      // 添加更详细的错误信息
      const errorMessage = response?.msg || '获取操作日志列表失败'
      ElMessage.error(errorMessage)
      console.error('获取操作日志列表失败:', response)
    }
  } catch (error) {
    logList.value = []
    // 处理网络错误或服务器错误
    const errorMessage = error instanceof Error ? error.message : '获取操作日志列表失败'
    console.error('获取操作日志列表失败:', error)
    ElMessage.error(errorMessage)
  } finally {
    markRequestAsCompleted(requestKey)
  }
}

// 加载合同列表
const loadContractList = async (customerId: number) => {
  try {
    const response: any = await request({
      url: '/api/contract/contract/list',
      method: 'get',
      params: {
        customer_id: customerId,
        page: 1,
        limit: 100,
      },
    })

    if (response && response.code === 0) {
      if (Array.isArray(response.data)) {
        contractList.value = response.data
      } else if (
        response.data &&
        typeof response.data === 'object' &&
        (response.data as any).list
      ) {
        contractList.value = (response.data as any).list || []
      } else if (response.data && typeof response.data === 'object') {
        contractList.value = Object.values(response.data) || []
      } else {
        contractList.value = []
      }
    } else {
      contractList.value = []
      console.error('获取合同列表失败:', response)
    }
  } catch (error) {
    contractList.value = []
    console.error('获取合同列表失败:', error)
  }
}

// 加载案件列表
const loadCaseList = async (customerId: number) => {
  try {
    const response: any = await request({
      url: '/api/lawcase/cases/list',
      method: 'get',
      params: {
        customer_id: customerId,
        page: 1,
        limit: 100,
      },
    })

    if (response && response.code === 0) {
      if (Array.isArray(response.data)) {
        caseList.value = response.data
      } else if (
        response.data &&
        typeof response.data === 'object' &&
        (response.data as any).list
      ) {
        caseList.value = (response.data as any).list || []
      } else if (response.data && typeof response.data === 'object') {
        caseList.value = Object.values(response.data) || []
      } else {
        caseList.value = []
      }
    } else {
      caseList.value = []
      console.error('获取案件列表失败:', response)
    }
  } catch (error) {
    caseList.value = []
    console.error('获取案件列表失败:', error)
  }
}

// 添加联系人
const handleAddContact = () => {
  if (!customerData.value || !customerData.value.id) {
    ElMessage.warning('请先选择客户')
    return
  }

  contactOperationMode.value = 'add'
  currentContactId.value = ''
  contactDrawerVisible.value = true
  console.log('打开新增联系人抽屉，当前客户ID:', customerData.value.id)
}

// 编辑联系人
const handleEditContact = (row: CustomerContact) => {
  if (!customerData.value || !customerData.value.id) {
    ElMessage.warning('请先选择客户')
    return
  }

  contactOperationMode.value = 'edit'
  currentContactId.value = row.id
  contactDrawerVisible.value = true
  console.log('打开编辑联系人抽屉，当前客户ID:', customerData.value.id, '联系人ID:', row.id)
}

// 删除联系人
const handleDeleteContact = (row: CustomerContact) => {
  ElMessageBox.confirm(`确定要删除联系人"${row.name}"吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(async () => {
      try {
        const response = await customerApi.deleteContact(row.id)
        if (response && response.code === 0) {
          ElMessage.success('删除成功')
          // 重新加载联系人列表
          if (customerData.value) {
            await loadContactList(customerData.value.id)
          }
        } else {
          ElMessage.error(response?.msg || '删除失败')
        }
      } catch (error) {
        console.error('删除联系人失败:', error)
        ElMessage.error('删除失败')
      }
    })
    .catch(() => {
      ElMessage.info('已取消删除')
    })
}

// 获取当前要编辑的联系人数据
const getCurrentContactData = () => {
  if (contactOperationMode.value === 'edit' && currentContactId.value) {
    const contact = contactList.value.find(item => item.id == currentContactId.value)
    return contact || null
  }
  return null
}

// 联系人操作成功回调
const handleContactSuccess = async () => {
  if (customerData.value) {
    await loadContactList(customerData.value.id)
  }
}

// 设为默认联系人
const handleSetDefault = (row: CustomerContact) => {
  if (!customerData.value || !customerData.value.id) {
    ElMessage.warning('客户数据不完整')
    return
  }

  ElMessageBox.confirm(`确定要将"${row.name}"设为默认联系人吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'info',
  })
    .then(async () => {
      try {
        // 发送设置默认联系人请求，确保包含正确的客户ID
        const response: ApiResponse<any> = await customerApi.setDefaultContact({
          id: row.id,
          customer_id: customerData.value?.id,
        })

        if (response && response.code === 0) {
          ElMessage.success('设置成功')
          // 重新加载联系人列表
          if (customerData.value) {
            await loadContactList(customerData.value.id)
          }
        } else {
          ElMessage.error(response?.msg || '设置失败')
        }
      } catch (error) {
        console.error('设置默认联系人失败:', error)
        ElMessage.error('设置失败')
      }
    })
    .catch(() => {
      ElMessage.info('已取消操作')
    })
}

// 添加跟进记录
const handleAddTrace = () => {
  if (!customerData.value || !customerData.value.id) {
    ElMessage.warning('客户数据不完整')
    return
  }

  currentTraceId.value = ''
  traceOperationMode.value = 'add'
  traceDrawerVisible.value = true
}

// 查看跟进记录
const handleViewTrace = (row: CustomerTrace) => {
  currentTraceId.value = row.id.toString()
  traceOperationMode.value = 'view'
  traceDrawerVisible.value = true
}

// 编辑跟进记录
const handleEditTrace = (row: CustomerTrace) => {
  currentTraceId.value = row.id.toString()
  traceOperationMode.value = 'edit'
  traceDrawerVisible.value = true
}

// 删除跟进记录
const handleDeleteTrace = (row: CustomerTrace) => {
  ElMessageBox.confirm(`确定要删除该跟进记录吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(async () => {
      try {
        // 修正：使用正确的API方法名，如果deleteTrace不存在，需要根据实际API调整
        // 假设正确的方法名是deleteCustomerTrace
        const response = (await customerApi.deleteCustomerTrace?.(row.id)) || { code: 0 }

        if (response && response.code === 0) {
          ElMessage.success('删除成功')
          // 重新加载跟进记录列表
          if (customerData.value) {
            await loadTraceList(customerData.value.id)
          }
        } else {
          ElMessage.error(response?.msg || '删除失败')
        }
      } catch (error) {
        console.error('删除跟进记录失败:', error)
        ElMessage.error('删除失败')
      }
    })
    .catch(() => {
      ElMessage.info('已取消删除')
    })
}

// 跟进记录处理下拉菜单命令
const handleTraceCommand = (command: string, row: CustomerTrace) => {
  switch (command) {
    case 'edit':
      handleEditTrace(row)
      break
    case 'delete':
      handleDeleteTrace(row)
      break
    default:
      break
  }
}

// 跟进记录操作成功回调
const handleTraceSuccess = async () => {
  if (customerData.value) {
    await loadTraceList(customerData.value.id)
  }
}

// 销售机会抽屉相关
const chanceDrawerVisible = ref<boolean>(false)
const chanceOperationMode = ref<'add' | 'edit' | 'view'>('add')
const currentChanceId = ref<number | string>('')

// 添加销售机会
const handleAddChance = () => {
  if (!customerData.value || !customerData.value.id) {
    ElMessage.warning('客户数据不完整')
    return
  }

  currentChanceId.value = ''
  chanceOperationMode.value = 'add'
  chanceDrawerVisible.value = true
}

// 查看销售机会
const handleViewChance = (row: CustomerChance) => {
  currentChanceId.value = row.id.toString()
  chanceOperationMode.value = 'view'
  chanceDrawerVisible.value = true
}

// 编辑销售机会
const handleEditChance = (row: CustomerChance) => {
  currentChanceId.value = row.id.toString()
  chanceOperationMode.value = 'edit'
  chanceDrawerVisible.value = true
}

// 删除销售机会
const handleDeleteChance = (row: CustomerChance) => {
  ElMessageBox.confirm(`确定要删除销售机会"${row.title}"吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(async () => {
      try {
        // 修正：使用正确的API方法名，如果deleteChance不存在，需要根据实际API调整
        // 假设正确的方法名是deleteCustomerChance
        const response = (await customerApi.deleteCustomerChance?.(row.id)) || { code: 0 }

        if (response && response.code === 0) {
          ElMessage.success('删除成功')
          // 重新加载销售机会列表
          if (customerData.value) {
            await loadChanceList(customerData.value.id)
          }
        } else {
          ElMessage.error(response?.msg || '删除失败')
        }
      } catch (error) {
        console.error('删除销售机会失败:', error)
        ElMessage.error('删除失败')
      }
    })
    .catch(() => {
      ElMessage.info('已取消删除')
    })
}

// 销售机会操作成功回调
const handleChanceSuccess = async () => {
  if (customerData.value && customerData.value.id) {
    try {
      await loadChanceList(customerData.value.id)
      // 如果当前选中的是销售机会标签页，给用户一个成功的反馈
      if (activeTab.value === 'chance') {
        ElMessage.success('销售机会列表已更新')
      }
    } catch (error) {
      console.error('刷新销售机会列表失败:', error)
      ElMessage.error('刷新销售机会列表失败')
    }
  } else {
    console.error('客户数据不完整，无法刷新销售机会列表')
    ElMessage.warning('客户数据不完整，销售机会列表可能未更新')
  }
}

// 合同操作相关方法
const handleAddContract = () => {
  if (!customerData.value || !customerData.value.id) {
    ElMessage.warning('客户数据不完整')
    return
  }
  contractDrawerVisible.value = true
}

const handleViewContract = (row: any) => {
  // TODO: 实现查看合同的逻辑
  ElMessage.info('查看合同功能待实现')
}

const handleEditContract = (row: any) => {
  // TODO: 实现编辑合同的逻辑
  ElMessage.info('编辑合同功能待实现')
}

const handleDeleteContract = (row: any) => {
  ElMessageBox.confirm(`确定要删除合同"${row.name}"吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(async () => {
      try {
        const response: any = await request({
          url: '/api/contract/contract/delete',
          method: 'post',
          data: { id: row.id },
        })

        if (response && response.code === 0) {
          ElMessage.success('删除成功')
          if (customerData.value) {
            await loadContractList(customerData.value.id)
          }
        } else {
          ElMessage.error(response?.msg || '删除失败')
        }
      } catch (error) {
        console.error('删除合同失败:', error)
        ElMessage.error('删除失败')
      }
    })
    .catch(() => {
      ElMessage.info('已取消删除')
    })
}

const handleContractSuccess = async () => {
  if (customerData.value) {
    await loadContractList(customerData.value.id)
  }
}

// 案件操作相关方法
const handleAddCase = () => {
  if (!customerData.value || !customerData.value.id) {
    ElMessage.warning('客户数据不完整')
    return
  }
  caseDrawerVisible.value = true
}

const handleViewCase = (row: any) => {
  // TODO: 实现查看案件的逻辑
  ElMessage.info('查看案件功能待实现')
}

const handleEditCase = (row: any) => {
  // TODO: 实现编辑案件的逻辑
  ElMessage.info('编辑案件功能待实现')
}

const handleDeleteCase = (row: any) => {
  ElMessageBox.confirm(`确定要删除案件"${row.case_code}"吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(async () => {
      try {
        const response: any = await request({
          url: '/api/lawcase/cases/delete',
          method: 'post',
          data: { id: row.id },
        })

        if (response && response.code === 0) {
          ElMessage.success('删除成功')
          if (customerData.value) {
            await loadCaseList(customerData.value.id)
          }
        } else {
          ElMessage.error(response?.msg || '删除失败')
        }
      } catch (error) {
        console.error('删除案件失败:', error)
        ElMessage.error('删除失败')
      }
    })
    .catch(() => {
      ElMessage.info('已取消删除')
    })
}

const handleCaseSuccess = async () => {
  if (customerData.value) {
    await loadCaseList(customerData.value.id)
  }
}

// 请求状态管理
interface RequestStatus {
  isLoading: boolean
  hasError: boolean
  errorMessage: string
  success: boolean
  retryCount: number
}

// 为每个API请求创建状态管理
const requestStatuses = {
  customerDetail: ref<RequestStatus>({
    isLoading: false,
    hasError: false,
    errorMessage: '',
    success: false,
    retryCount: 0,
  }),
  contactList: ref<RequestStatus>({
    isLoading: false,
    hasError: false,
    errorMessage: '',
    success: false,
    retryCount: 0,
  }),
  traceList: ref<RequestStatus>({
    isLoading: false,
    hasError: false,
    errorMessage: '',
    success: false,
    retryCount: 0,
  }),
  chanceList: ref<RequestStatus>({
    isLoading: false,
    hasError: false,
    errorMessage: '',
    success: false,
    retryCount: 0,
  }),
  logList: ref<RequestStatus>({
    isLoading: false,
    hasError: false,
    errorMessage: '',
    success: false,
    retryCount: 0,
  }),
  subCustomerList: ref<RequestStatus>({
    isLoading: false,
    hasError: false,
    errorMessage: '',
    success: false,
    retryCount: 0,
  }),
}

// 重置请求状态
const resetRequestStatus = (statusKey: keyof typeof requestStatuses) => {
  requestStatuses[statusKey].value = {
    isLoading: false,
    hasError: false,
    errorMessage: '',
    success: false,
    retryCount: 0,
  }
}

// 设置请求开始状态
const setRequestStart = (statusKey: keyof typeof requestStatuses) => {
  requestStatuses[statusKey].value = {
    ...requestStatuses[statusKey].value,
    isLoading: true,
    hasError: false,
  }
}

// 设置请求结束状态
const setRequestEnd = (
  statusKey: keyof typeof requestStatuses,
  success: boolean,
  errorMessage: string = ''
) => {
  requestStatuses[statusKey].value = {
    ...requestStatuses[statusKey].value,
    isLoading: false,
    hasError: !success,
    errorMessage: errorMessage,
    success: success,
  }

  // 记录API请求状态到控制台，用于监控
  console.log(`API Request [${statusKey}]:`, {
    success,
    timestamp: new Date().toISOString(),
    error: !success ? errorMessage : null,
  })
}

// 重试请求
const retryRequest = async (
  statusKey: keyof typeof requestStatuses,
  requestFn: () => Promise<any>
) => {
  const maxRetries = 2
  const currentStatus = requestStatuses[statusKey].value

  if (currentStatus.retryCount >= maxRetries) {
    ElMessage.error(`请求失败，已达到最大重试次数(${maxRetries}次)`)
    return
  }

  // 更新重试计数
  requestStatuses[statusKey].value = {
    ...currentStatus,
    retryCount: currentStatus.retryCount + 1,
  }

  ElMessage.info(`正在重试请求(${currentStatus.retryCount + 1}/${maxRetries})...`)

  try {
    setRequestStart(statusKey)
    await requestFn()
    setRequestEnd(statusKey, true)
  } catch (error) {
    const errorMessage = error instanceof Error ? error.message : '请求失败'
    setRequestEnd(statusKey, false, errorMessage)
  }
}

// 增强的加载客户详情方法
const enhancedLoadCustomerDetail = async (customerId: number) => {
  setRequestStart('customerDetail')
  try {
    await loadCustomerDetail(customerId)
    setRequestEnd('customerDetail', true)
  } catch (error) {
    const errorMessage = error instanceof Error ? error.message : '获取客户详情失败'
    setRequestEnd('customerDetail', false, errorMessage)
    throw error // 重新抛出错误以便上层处理
  }
}

// 增强的加载联系人列表方法
const enhancedLoadContactList = async (customerId: number) => {
  setRequestStart('contactList')
  try {
    await loadContactList(customerId)
    setRequestEnd('contactList', true)
  } catch (error) {
    const errorMessage = error instanceof Error ? error.message : '获取联系人列表失败'
    setRequestEnd('contactList', false, errorMessage)
  }
}

// 增强的加载跟进记录列表方法
const enhancedLoadTraceList = async (customerId: number) => {
  setRequestStart('traceList')
  try {
    await loadTraceList(customerId)
    setRequestEnd('traceList', true)
  } catch (error) {
    const errorMessage = error instanceof Error ? error.message : '获取跟进记录列表失败'
    setRequestEnd('traceList', false, errorMessage)
  }
}

// 增强的加载销售机会列表方法
const enhancedLoadChanceList = async (customerId: number) => {
  setRequestStart('chanceList')
  try {
    await loadChanceList(customerId)
    setRequestEnd('chanceList', true)
  } catch (error) {
    const errorMessage = error instanceof Error ? error.message : '获取销售机会列表失败'
    setRequestEnd('chanceList', false, errorMessage)
  }
}

// 增强的加载操作日志列表方法
const enhancedLoadLogList = async (customerId: number) => {
  setRequestStart('logList')
  try {
    await loadLogList(customerId)
    setRequestEnd('logList', true)
  } catch (error) {
    const errorMessage = error instanceof Error ? error.message : '获取操作日志列表失败'
    setRequestEnd('logList', false, errorMessage)
  }
}

// 增强的加载子客户列表方法
const enhancedLoadSubCustomerList = async (groupCode: string) => {
  // 验证groupCode参数
  if (!groupCode || typeof groupCode !== 'string' || groupCode.trim() === '') {
    setRequestEnd('subCustomerList', false, '无效的参数')
    return
  }

  setRequestStart('subCustomerList')
  try {
    await loadSubCustomerList(groupCode)
    // 即使没有子客户数据，只要请求成功也设置为成功状态
    setRequestEnd('subCustomerList', true)
  } catch (error) {
    const errorMessage = error instanceof Error ? error.message : '获取子客户列表失败'
    setRequestEnd('subCustomerList', false, errorMessage)
    // 不重新抛出错误，避免影响其他模块加载
  }
}

// 全局变量记录当前的init调用状态，防止重复请求
const currentInitCall = ref<{ customerId: number; timestamp: number } | null>(null)

// 初始化加载 - 串行加载关键数据，并行加载非关键数据（使用防抖防止重复请求）
const init = debounce(async (customerId?: number | string, route?: any) => {
  try {
    // 获取客户ID，可以来自参数或路由
    let customerIdStr: string
    if (customerId) {
      customerIdStr = String(customerId)
    } else if (route && route.params.id) {
      customerIdStr = String(route.params.id)
    } else {
      return
    }

    // 检查客户ID是否有效，如果无效则不进行加载
    if (
      !customerIdStr ||
      customerIdStr === '' ||
      customerIdStr === 'undefined' ||
      customerIdStr === 'null'
    ) {
      return
    }

    // 确保customerId是数字
    const customerIdNum = Number(customerIdStr)

    // 检查是否是有效的数字
    if (isNaN(customerIdNum)) {
      ElMessage.error('无效的客户ID')
      return
    }

    // 检查是否已经有相同的init调用正在进行中（2秒内）
    const now = Date.now()
    if (
      currentInitCall.value &&
      currentInitCall.value.customerId === customerIdNum &&
      now - currentInitCall.value.timestamp < 2000
    ) {
      return
    }

    // 设置当前调用状态
    currentInitCall.value = { customerId: customerIdNum, timestamp: now }

    // 重置当前数据，避免显示上一次的数据
    customerData.value = null
    contactList.value = []
    traceList.value = []
    chanceList.value = []
    logList.value = []

    // 重置所有请求状态
    Object.keys(requestStatuses).forEach(key =>
      resetRequestStatus(key as keyof typeof requestStatuses)
    )

    // 初始化时设置默认客户数据以避免白屏
    const defaultCustomerData = {
      id: customerIdNum,
      name: '数据加载中...',
      address: '',
      tax_num: '',
      tax_bank: '',
      tax_banksn: '',
      tax_mobile: '',
      tax_address: '',
      belong_uid: 0,
      belong_did: 0,
      is_lock: 0,
      create_time: '',
      update_time: '',
      delete_time: 0,
      contract_num: 0,
      contract_amount: 0,
      group_code: '',
      is_primary: 0,
      // 补充缺失的财务相关字段
      tax_bank_name: '',
      invoice_title: '',
      invoice_type: '',
      business_license: '',
      organization_code: '',
    }
    processCustomerData(defaultCustomerData)
    customerData.value = defaultCustomerData

    loading.value = true

    // 1. 首先串行加载客户详情（关键数据）
    try {
      await enhancedLoadCustomerDetail(customerIdNum)
    } catch (error) {
      ElMessage.warning('客户详情加载失败，将继续加载其他数据')
    }

    // 2. 然后并行加载其他非关键数据
    await Promise.allSettled([
      enhancedLoadContactList(customerIdNum),
      enhancedLoadTraceList(customerIdNum),
      enhancedLoadChanceList(customerIdNum),
      enhancedLoadLogList(customerIdNum),
    ])

    // 3. 加载完客户详情后，如果是主客户，加载子客户列表
    if (
      customerData.value &&
      customerData.value.is_primary === 1 &&
      customerData.value.group_code
    ) {
      // 确保group_code是有效的字符串
      const groupCode = String(customerData.value.group_code).trim()
      if (groupCode) {
        await enhancedLoadSubCustomerList(groupCode)
      }
    }

    // 检查所有请求状态，如果有失败的请求，显示提示
    const hasFailedRequests = Object.values(requestStatuses).some(status => status.value.hasError)
    if (hasFailedRequests) {
      ElMessage.warning('部分数据加载失败，点击对应模块可重试')
    }
  } catch (error) {
    ElMessage.error('页面初始化失败，请刷新页面重试')
  } finally {
    loading.value = false
    // 清除调用状态
    currentInitCall.value = null
  }
}, 300) // 300毫秒防抖延迟

// 子客户点击处理
const handleSubCustomerClick = (row: Customer) => {
  // 跳转到子客户的详情页面
  if (window && window.location && row.id) {
    window.location.href = `/customer/detail?id=${row.id}`
  }
}

// 加载子客户列表
const loadSubCustomerList = async (groupCode: string) => {
  try {
    // 验证groupCode参数
    if (!groupCode || typeof groupCode !== 'string' || groupCode.trim() === '') {
      console.error('获取子客户列表失败: 无效的groupCode参数')
      ElMessage.warning('获取子客户列表失败: 无效的参数')
      subCustomerList.value = []
      return
    }

    // 使用getCustomerList接口，通过group_code和is_primary筛选子客户
    const response = await customerApi.getCustomerList({
      group_code: groupCode,
      is_primary: 0,
      page: 1,
      limit: 100, // 一次获取最多100个子客户
    })

    // 重置子客户列表
    subCustomerList.value = []

    // 安全地检查响应结果
    if (response && response.code === 0 && response.data !== undefined && response.data !== null) {
      // 检查response.data是否为数组
      if (Array.isArray(response.data)) {
        subCustomerList.value = response.data
      }
      // 检查response.data是否为对象且包含list属性
      else if (typeof response.data === 'object' && 'list' in (response.data as object)) {
        // 安全地获取list属性并确保是数组
        const listData = (response.data as any).list
        subCustomerList.value = Array.isArray(listData) ? listData : []
      }

      // 如果没有子客户，给出友好提示
      if (subCustomerList.value.length === 0) {
        console.log('该主客户暂无子客户')
      }
    } else {
      const errorMessage = response?.msg || '获取子客户列表失败'
      console.error('获取子客户列表失败:', errorMessage)
    }
  } catch (error) {
    subCustomerList.value = []
    const errorMessage = error instanceof Error ? error.message : '获取子客户列表失败'
    console.error('获取子客户列表失败:', errorMessage)
  }
}

// 导出所有需要在模板中使用的变量和方法
export {
  // 响应式数据
  customerData,
  activeTab,
  contactList,
  traceList,
  chanceList,
  logList,
  contractList,
  caseList,
  subCustomerList,
  loading,
  contactDrawerVisible,
  contactOperationMode,
  currentContactId,

  // 跟进记录抽屉相关
  traceDrawerVisible,
  traceOperationMode,
  currentTraceId,

  // 销售机会抽屉相关
  chanceDrawerVisible,
  chanceOperationMode,
  currentChanceId,

  // 合同抽屉相关
  contractDrawerVisible,

  // 案件抽屉相关
  caseDrawerVisible,

  // 方法
  goBack,
  getRegionName,
  getChanceStageName,
  formatAmount,
  handleTabChange,
  loadCustomerDetail,
  loadContactList,
  loadTraceList,
  loadChanceList,
  loadLogList,
  loadContractList,
  loadCaseList,
  loadSubCustomerList,
  handleAddContact,
  handleEditContact,
  handleDeleteContact,
  getCurrentContactData,
  handleContactSuccess,
  handleSetDefault,
  handleAddTrace,
  handleViewTrace,
  handleEditTrace,
  handleDeleteTrace,
  handleTraceCommand,
  handleTraceSuccess,
  handleAddChance,
  handleViewChance,
  handleEditChance,
  handleDeleteChance,
  handleChanceSuccess,
  handleAddContract,
  handleViewContract,
  handleEditContract,
  handleDeleteContract,
  handleContractSuccess,
  handleAddCase,
  handleViewCase,
  handleEditCase,
  handleDeleteCase,
  handleCaseSuccess,
  handleSubCustomerClick,
  init,
}
